package com.ruoyi.mdkt.service.impl;

import com.ruoyi.mdkt.entity.*;
import com.ruoyi.mdkt.mapper.TaskReceiveMapper;
import com.ruoyi.mdkt.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gwl
 * @since 2022-10-25
 */
@Service
public class TaskReceiveServiceImpl extends ServiceImpl<TaskReceiveMapper, TaskReceive> implements TaskReceiveService {

    @Autowired
    private TaskReceiveMapper taskReceiveMapper;
    @Autowired
    private TaskInfoService taskInfoService;
    @Autowired
    private TaskScoreService taskScoreService;
    @Autowired
    private ScoreLogService scoreLogService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private StudentService studentService;

    @Override
    public boolean isSigned(Long userId, Long taskInfoId) {
        TaskReceive signTaskReceiveByUserIdAndTaskInfoId = taskReceiveMapper.getSignTaskReceiveByUserIdAndTaskInfoId(String.valueOf(userId), String.valueOf(taskInfoId));
        if (signTaskReceiveByUserIdAndTaskInfoId == null) {
            return false;
        } else {
            return true;
        }
    }


    @Override
    public Integer saveTaskReceiveList(List<TaskReceive> list, Long userId) {
        Integer count = 0;
        Integer score = 0;
        Long taskId = list.get(0).getTaskId();
        Task task = taskService.getById(taskId);
        for (int i = 0; i < list.size(); i++) {
            TaskReceive taskReceive = list.get(i);
            TaskInfo taskInfo = taskInfoService.getById(taskReceive.getTaskInfoId());
            taskReceive.setQuestion(taskInfo.getQuestion());
            taskReceive.setType(taskInfo.getType());
            taskReceive.setStudentUserId(userId);
            switch (taskReceive.getType()) {
                case 1:
                case 2:
                    if (taskReceive.getAnswer().equals(taskInfo.getAnswer())) {
                        taskReceive.setScore(taskInfo.getScore());
                        score = score + taskInfo.getScore();
                    } else {
                        taskReceive.setScore(0);
                    }
                    break;
                case 3:
                    taskReceive.setScore(0);
                    break;
            }
            taskReceiveMapper.insert(taskReceive);
            count++;
        }
        TaskScore taskScore = new TaskScore();
        taskScore.setTaskId(taskId);
        taskScore.setStudentUserId(userId);
        taskScore.setScore(score);
        taskScoreService.save(taskScore);
        scoreLogService.saveScoreLog(score, "作业得分", userId, task.getCourseId());
        Student student = studentService.getById(userId);
        student.setAssets(student.getAssets() + score);
        studentService.updateById(student);
        return count;
    }
}
